package com.ubing.boot.notesforjava.test.file;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class ScatteringRead {
    public static void main(String[] args) {
        // 读
//        try (FileChannel channel = new RandomAccessFile("D:\\项目\\notesforjava\\src\\main\\java\\com\\ubing\\boot\\notesforjava\\test\\file\\data.txt", "r").getChannel()) {
//            ByteBuffer a = ByteBuffer.allocate(3);
//            ByteBuffer b = ByteBuffer.allocate(3);
//            ByteBuffer c = ByteBuffer.allocate(5);
//            channel.read(new ByteBuffer[]{a, b, c});
//            printBuffer(a);
//            printBuffer(b);
//            printBuffer(c);
//
//
//        } catch (IOException e) {
//        }

        // 写
        ByteBuffer b1 = StandardCharsets.UTF_8.encode("hello");
        ByteBuffer b2 = StandardCharsets.UTF_8.encode("时间飞机");
        ByteBuffer b3 = StandardCharsets.UTF_8.encode("12312");
        try (FileChannel channel = new RandomAccessFile("data.txt", "rw").getChannel()) {
            channel.write(new ByteBuffer[]{b1, b2, b3});
        } catch (IOException e) {
        };

    }


    private static void printBuffer(ByteBuffer buffer){
        buffer.flip();// 将buffer指针位置 置为0
        while (buffer.hasRemaining()){ // 是否有剩余数据
            byte b = buffer.get();
            System.out.println((char) b);
        }
    }
}
